<?php
namespace app\index\controller;

use app\index\controller\Base;
use think\Db;
use think\Session;

class Order extends Base
{
    /**
     * 创建订单
     * @return mixed
     */
    public function OrderFound(){
        //商品ID
        $GoodsID = Param('goods_id');
        //拼团方式
        $pttype = Param('type');
        if($pttype){
            $pttype = $pttype;
        }else{
            $pttype = 0;
        }
        $this->assign('pttype',$pttype);
        //拼团编号
        $pt_id = Param('pt_id');
        if($pt_id){
            $pt_id = $pt_id;
        }else{
            $pt_id = 0;
        }
         $this->assign('pt_id',$pt_id);
        //商品信息
        $GoodsInfo = GoodsInfo(['id'=>$GoodsID]);
        $price = $GoodsInfo['price'];
        $this->assign('GoodsInfo',$GoodsInfo);
        //会员信息
        $UserInfo = UserInfo(['id'=>Session::get('user_id')]);
        $this->assign('UserInfo',$UserInfo);

        
        if($GoodsInfo['goods_type'] == 3){
            if($UserInfo['level'] == 8){
                $GoodsInfo['price'] = $GoodsInfo['hhrprice'];
            }elseif($UserInfo['level'] == 7){
                $GoodsInfo['price'] = $GoodsInfo['shprice'];
            }elseif($UserInfo['level'] == 6){
                $GoodsInfo['price'] = $GoodsInfo['sjprice'];
            }elseif($UserInfo['level'] == 5){
                $GoodsInfo['price'] = $GoodsInfo['qxprice'];
            }elseif($UserInfo['level'] == 4){
                $GoodsInfo['price'] = $GoodsInfo['dpprice'];
            }elseif($UserInfo['level'] == 3){
                $GoodsInfo['price'] = $GoodsInfo['dlprice'];
            }elseif($UserInfo['level'] == 2){
                $GoodsInfo['price'] = $GoodsInfo['hyprice'];
            }else{
                $GoodsInfo['price'] = $GoodsInfo['price'];
            }
        }elseif($GoodsInfo['goods_type'] == 5 && $pttype == 1){
            $GoodsInfo['price'] = $GoodsInfo['quan'];
        }else{
            $GoodsInfo['price'] = $GoodsInfo['price'];
        }
        //地址信息
        $Address = Db::name('user_address')->where(['user_id'=>$UserInfo['id'],'is_default'=>1])->find();
        $this->assign('Address',$Address);
        
        //所有省
        $sheng = array();
        $sheng = array("北京"=>"d1","上海"=>"d2","天津"=>"d3","重庆"=>"d4","河北"=>"d5","山西"=>"d6","河南"=>"d7","辽宁"=>"d8","吉林"=>"d8","黑龙江"=>"d10","内蒙古"=>"d11","江苏"=>"d12","山东"=>"d13","安徽"=>"d14","浙江"=>"d15","福建"=>"d16","湖北"=>"d17","湖南"=>"d18","广东"=>"d19","广西"=>"d20","江西"=>"d21","四川"=>"d22","海南"=>"d23","贵州"=>"d24","云南"=>"d25","西藏"=>"d26","陕西"=>"d27","甘肃"=>"d28","青海"=>"d29","宁夏"=>"d30","新疆"=>"d31","台湾"=>"d32","钓鱼岛"=>"d33","港澳"=>"d34");
        //判断地址是否存在  算邮费
        if($Address){
            //拿出省
            $address = explode(' ',$Address['area'])[0];
            $canshu = $sheng[$address];
            // $you = Db::name('youfei')->where(['sheng'=>$address])->find()['youfei']; 
            $you = $GoodsInfo[$canshu];
        }else{
            $you = 0.00;
        }
       
        
        $this->assign('you',$you);
        //Post请求
        if(IsPost()){
            //请求数据
            $Data = Param();

            if($GoodsInfo['goods_type'] == 2 && $UserInfo['level'] >= $GoodsInfo['is_sheng'] + 1){
                return ['status'=>0,'message'=>'您已经是vip或者代理,请您去复购专区购买！'];
            }

            if($GoodsInfo['goods_type'] == 3 && $UserInfo['level'] < 2){
                return ['status'=>0,'message'=>'vip以上身份才能购买'];
            }

            //判断限购  秒杀
            if($GoodsInfo['goods_type'] == 4){
                if($Data['num'] > $GoodsInfo['xiangou']){
                    return ['status'=>0,'message'=>'超过限购数量！'];
                }
            }
            
            //游客不能发起拼团
            if($GoodsInfo['goods_type'] == 5){
                if($UserInfo['level'] == 1){
                    return ['status'=>0,'message'=>'游客不能发起拼团！'];
                }
            }
            
            if(empty($Address)){
                return ['status'=>2,'message'=>'请添加收货地址！'];
            }
            
            //发起拼团  插入数据  其他不用
            if($pttype == 1){
                $pt['pt_id'] = date('YmdHis',time()).randNumber(3);//拼团编号
                $pt['goods_id'] = $GoodsInfo['id'];//商品ID
                $pt['chuang'] = $UserInfo['id'];//创建人
                $pt['can'] = '';//参与人
                $pt['add_time'] = time();//创建时间
                $pt['quan'] = $GoodsInfo['quan'];//拼团券
                $pt['price'] = $price;//其他人价格
                $pt['pt_people'] = $GoodsInfo['allpeople'];//拼团人数
                $pt['can_people'] = 0;//一品人数
                $pt['get_people'] = $GoodsInfo['getpeople'];//得到人数
                $pt['hongbao'] = $GoodsInfo['backred'];//红包
                $pt['status'] = 0;//状态
                $pt['zhong'] = '';//中奖
            }
            // var_dump($pt_id);
            // var_dump($Data);
            //订单信息
            $OrderAdd['user_id'] = Session::get('user_id'); //用户ID
            $OrderAdd['order_id'] = date('YmdHis',time()).randNumber(3);    //订单编号
            // $OrderAdd['amount'] = $GoodsInfo['price'] * $Data['num'] ;   //总价
            $OrderAdd['amount'] = $GoodsInfo['price'] * $Data['num'] + $Data['youfei'];   //总价
            $OrderAdd['pay_point'] = $GoodsInfo['price']*$GoodsInfo['proportion'] * $Data['num'];   //可抵用炁点
            $OrderAdd['goods_id'] = $GoodsInfo['id'];   //商品ID
            $OrderAdd['num'] = $Data['num'];    //购买数量
            $OrderAdd['name'] = $Address['name'];   //收货姓名
            $OrderAdd['phone'] = $Address['phone']; //联系电话
            $OrderAdd['address'] = $Address['area'].$Address['address'];    //收货地址
            $OrderAdd['add_time'] = time(); //下单时间
            $OrderAdd['order_type'] = $GoodsInfo['goods_type']; //商品类型
            $OrderAdd['order_level'] = $GoodsInfo['goods_level']; //商品等级
            $OrderAdd['reward_1'] = $GoodsInfo['reward_1'] * $Data['num']; //一代奖励
            $OrderAdd['reward_2'] = $GoodsInfo['reward_2'] * $Data['num']; //二代奖励
            $OrderAdd['reward_3'] = $GoodsInfo['reward_3'] * $Data['num']; //分公司业绩奖
            $OrderAdd['reward_4'] = $GoodsInfo['reward_4'] * $Data['num']; //分公司同级奖
            $OrderAdd['reward_5'] = $GoodsInfo['reward_5'] * $Data['num']; //系统业绩奖
            $OrderAdd['reward_6'] = $GoodsInfo['reward_6'] * $Data['num']; //系统同级奖
            
            if($pttype == 1){
                $OrderAdd['pt_id'] = $pt['pt_id']; 
            }
            if($pt_id){
                $OrderAdd['pt_id'] = $Data['pt_id']; 
            }
            // var_dump($OrderAdd['pt_id']);die;
            //向表中添加订单
            if(Db::name('user_order')->insert($OrderAdd)){
                if($pttype == 1){
                    Db::name('user_pt')->insert($pt);
                }
                return ['status'=>1,'message'=>'订单创建成功','order_id'=>$OrderAdd['order_id']];
            }else{
                return ['status'=>0,'message'=>'系统错误，请重试！'];
            }
        }
        return $this->fetch('FoundOrder');
    }

    /**
     * 创建订单
     * @return mixed
     */
    public function OrderFound_1(){
        //商品ID
        $GoodsID = Param('goods_id');
        $this->assign('goods_id',$GoodsID);
        //分割处理所有商品
        $goods_id = explode(',', $GoodsID);
        
        //拼团方式
        $pttype = Param('type');
        if($pttype){
            $pttype = $pttype;
        }else{
            $pttype = 0;
        }
        $this->assign('pttype',$pttype);
        //拼团编号
        $pt_id = Param('pt_id');
        if($pt_id){
            $pt_id = $pt_id;
        }else{
            $pt_id = 0;
        }
         $this->assign('pt_id',$pt_id);

         //会员信息
        $UserInfo = UserInfo(['id'=>Session::get('user_id')]);
        $this->assign('UserInfo',$UserInfo);

        //所有省
        $sheng = array();
        $sheng = array("北京"=>"d1","上海"=>"d2","天津"=>"d3","重庆"=>"d4","河北"=>"d5","山西"=>"d6","河南"=>"d7","辽宁"=>"d8","吉林"=>"d8","黑龙江"=>"d10","内蒙古"=>"d11","江苏"=>"d12","山东"=>"d13","安徽"=>"d14","浙江"=>"d15","福建"=>"d16","湖北"=>"d17","湖南"=>"d18","广东"=>"d19","广西"=>"d20","江西"=>"d21","四川"=>"d22","海南"=>"d23","贵州"=>"d24","云南"=>"d25","西藏"=>"d26","陕西"=>"d27","甘肃"=>"d28","青海"=>"d29","宁夏"=>"d30","新疆"=>"d31","台湾"=>"d32","钓鱼岛"=>"d33","港澳"=>"d34");

        //地址信息
        $Address = Db::name('user_address')->where(['user_id'=>$UserInfo['id'],'is_default'=>1])->find();
        $this->assign('Address',$Address);

        //定义商品总价
        $TotalPrice = 0;
         //获取商品信息
        foreach ($goods_id as $key => $value) {
            $GoodsInfo = GoodsInfo(['id'=>$value]);
            if($GoodsInfo['goods_type'] == 3){
                if($UserInfo['level'] == 8){
                    $GoodsInfo['price'] = $GoodsInfo['hhrprice'];
                }elseif($UserInfo['level'] == 7){
                    $GoodsInfo['price'] = $GoodsInfo['shprice'];
                }elseif($UserInfo['level'] == 6){
                    $GoodsInfo['price'] = $GoodsInfo['sjprice'];
                }elseif($UserInfo['level'] == 5){
                    $GoodsInfo['price'] = $GoodsInfo['qxprice'];
                }elseif($UserInfo['level'] == 4){
                    $GoodsInfo['price'] = $GoodsInfo['dpprice'];
                }elseif($UserInfo['level'] == 3){
                    $GoodsInfo['price'] = $GoodsInfo['dlprice'];
                }elseif($UserInfo['level'] == 2){
                    $GoodsInfo['price'] = $GoodsInfo['hyprice'];
                }else{
                    $GoodsInfo['price'] = $GoodsInfo['price'];
                }
            }elseif($GoodsInfo['goods_type'] == 5 && $pttype == 1){
                $GoodsInfo['price'] = $GoodsInfo['quan'];
            }else{
                $GoodsInfo['price'] = $GoodsInfo['price'];
            }

            //获取购物车数量
            $num = Db::name('user_cart')->where(['user_id'=>Session::get('user_id'),'goods_id'=>$GoodsInfo['id']])->find()['num'];
            $GoodsInfo['num'] = $num;

            //判断地址是否存在  算邮费
            if($Address){
                //拿出省
                $address = explode(' ',$Address['area'])[0];
                $canshu = $sheng[$address];
                // $you = Db::name('youfei')->where(['sheng'=>$address])->find()['youfei']; 
                $you = $GoodsInfo[$canshu];
            }else{
                $you = 0.00;
            }
            //邮费所有  取最高
            $youfei[] = $you;
            //商品信息
            $goods[] = $GoodsInfo;

            $TotalPrice = $TotalPrice + $GoodsInfo['price']*$num;

            //每个商品数量
            $nums[] = $num;
        }
        $this->assign('goods',$goods);
        //邮费取最大值
        $postmoney = max($youfei);
        $this->assign('you',$postmoney);

        $TotalMoney = $TotalPrice + $postmoney;  //总计金额
        $this->assign('TotalMoney',$TotalMoney);
        //Post请求
        if(IsPost()){
            //请求数据
            $Data = Param();
            
            //订单信息
            $OrderAdd['user_id'] = Session::get('user_id'); //用户ID
            $OrderAdd['order_id'] = date('YmdHis',time()).randNumber(3);    //订单编号
            $OrderAdd['amount'] = $TotalMoney;   //总价
            $OrderAdd['pay_point'] = 0;   //可抵用炁点
            $OrderAdd['goods_id'] = $GoodsID;   //商品ID
            $OrderAdd['num'] = implode(',',$nums);    //购买数量
            $OrderAdd['name'] = $Address['name'];   //收货姓名
            $OrderAdd['phone'] = $Address['phone']; //联系电话
            $OrderAdd['address'] = $Address['area'].$Address['address'];    //收货地址
            $OrderAdd['add_time'] = time(); //下单时间
            $OrderAdd['order_type'] = 3; //商品类型
            $OrderAdd['order_level'] = 3; //商品等级
            $OrderAdd['reward_1'] = 0; //一代奖励
            $OrderAdd['reward_2'] = 0; //二代奖励
            $OrderAdd['reward_3'] = 0; //分公司业绩奖
            $OrderAdd['reward_4'] = 0; //分公司同级奖
            $OrderAdd['reward_5'] = 0; //系统业绩奖
            $OrderAdd['reward_6'] = 0; //系统同级奖
            
            if($pttype == 1){
                $OrderAdd['pt_id'] = $pt['pt_id']; 
            }
            if($pt_id){
                $OrderAdd['pt_id'] = $Data['pt_id']; 
            }

            //结算订单的时候  将购物车删除
            $cargoods = explode(',', $GoodsID);
            //向表中添加订单
            if(Db::name('user_order')->insert($OrderAdd)){
                if($pttype == 1){
                    Db::name('user_pt')->insert($pt);
                }
                foreach ($cargoods as $v) {
                    Db::name('user_cart')->where(['user_id'=>$UserInfo['id'],'goods_id'=>$v])->delete();
                }
                return ['status'=>1,'message'=>'订单创建成功','order_id'=>$OrderAdd['order_id']];
            }else{
                return ['status'=>0,'message'=>'系统错误，请重试！'];
            }
        }
        return $this->fetch('FoundOrder_1');
    }

    /**
     * 订单列表
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function OrderList(){
        //会员信息
        $UserInfo = UserInfo(['id'=>Session::get('user_id')]);
        $this->assign('UserInfo',$UserInfo);
        //全部订单
        $Where['user_id'] = Session::get('user_id');
        $OrderListAll = Db::name('user_order')->where($Where)->order('add_time desc')->select();
        foreach($OrderListAll as $k=>$v){
            //所有商品id
            $goods_id = explode(',', $OrderListAll[$k]['goods_id']);
            $muns = explode(',', $OrderListAll[$k]['num']);
            foreach ($goods_id as $key=>$val) {
                $GoodsInfo = Db::name('goods')->where(['id'=>$val])->find();
                $goods['logo_url'] = $GoodsInfo['logo_url'];
                $goods['goods_name'] = $GoodsInfo['name'];
//                 $goods['price'] = $v['price'];
                $goods['name'] = $GoodsInfo['name'];
                $goods['num'] = $muns[$key];
                if($GoodsInfo['goods_type'] == 3){
                    if($UserInfo['level'] == 6){
                        $goods['price'] = $GoodsInfo['shprice'];
                    }elseif($UserInfo['level'] == 5){
                        $goods['price'] = $GoodsInfo['sjprice'];
                    }elseif($UserInfo['level'] == 4){
                        $goods['price'] = $GoodsInfo['qxprice'];
                    }elseif($UserInfo['level'] == 3){
                        $goods['price'] = $GoodsInfo['dpprice'];
                    }elseif($UserInfo['level'] == 2){
                        $goods['price'] = $GoodsInfo['hyprice'];
                    }else{
                        $goods['price'] = $GoodsInfo['price'];
                    }
                }else{
                    $goods['price'] = $GoodsInfo['price'];
                }
                $OrderListAll[$k]['goods'][] = $goods;
            }
        }
        // echo "<pre>";
        // var_dump($OrderListAll);die;
        $this->assign('OrderListAll',$OrderListAll);

        //待付款订单
        $Where['status'] = 0;
        $OrderList_0 = Db::name('user_order')->where($Where)->order('add_time desc')->select();
        foreach($OrderList_0 as $k=>$v){
            $GoodsInfo = Db::name('goods')->where(['id'=>$OrderList_0[$k]['goods_id']])->find();
            $OrderList_0[$k]['logo_url'] = $GoodsInfo['logo_url'];
            $OrderList_0[$k]['goods_name'] = $GoodsInfo['name'];
            $OrderList_0[$k]['price'] = $GoodsInfo['price'];
        }
        $this->assign('OrderList_0',$OrderList_0);

        //待发货订单
        $Where['status'] = 1;
        $OrderList_1 = Db::name('user_order')->where($Where)->order('add_time desc')->select();
        foreach($OrderList_1 as $k=>$v){
            $GoodsInfo = Db::name('goods')->where(['id'=>$OrderList_1[$k]['goods_id']])->find();
            $OrderList_1[$k]['logo_url'] = $GoodsInfo['logo_url'];
            $OrderList_1[$k]['goods_name'] = $GoodsInfo['name'];
            $OrderList_1[$k]['price'] = $GoodsInfo['price'];
        }
        $this->assign('OrderList_1',$OrderList_1);

        //待收货订单
        $Where['status'] = 2;
        $OrderList_2 = Db::name('user_order')->where($Where)->order('add_time desc')->select();
        foreach($OrderList_2 as $k=>$v){
            $GoodsInfo = Db::name('goods')->where(['id'=>$OrderList_2[$k]['goods_id']])->find();
            $OrderList_2[$k]['logo_url'] = $GoodsInfo['logo_url'];
            $OrderList_2[$k]['goods_name'] = $GoodsInfo['name'];
            $OrderList_2[$k]['price'] = $GoodsInfo['price'];
        }
        $this->assign('OrderList_2',$OrderList_2);

        //已完成订单
        $Where['status'] = 3;
        $OrderList_3 = Db::name('user_order')->where($Where)->order('add_time desc')->select();
        foreach($OrderList_3 as $k=>$v){
            $GoodsInfo = Db::name('goods')->where(['id'=>$OrderList_3[$k]['goods_id']])->find();
            $OrderList_3[$k]['logo_url'] = $GoodsInfo['logo_url'];
            $OrderList_3[$k]['goods_name'] = $GoodsInfo['name'];
            $OrderList_3[$k]['price'] = $GoodsInfo['price'];
        }
        $this->assign('OrderList_3',$OrderList_3);
        
        //待拼团
        $Where['status'] = 4;
        $OrderList_4 = Db::name('user_order')->where($Where)->order('add_time desc')->select();
        foreach($OrderList_4 as $k=>$v){
            $GoodsInfo = Db::name('goods')->where(['id'=>$OrderList_4[$k]['goods_id']])->find();
            $OrderList_4[$k]['logo_url'] = $GoodsInfo['logo_url'];
            $OrderList_4[$k]['goods_name'] = $GoodsInfo['name'];
            $OrderList_4[$k]['price'] = $GoodsInfo['price'];
        }
        $this->assign('OrderList_4',$OrderList_4);

        return $this->fetch('OrderList');
    }

    



    /**
     * 订单支付
     * @return array|mixed
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function OrderPay(){
        //订单信息
        $OrderID = Param('order_id');
        $OrderInfo = Db::name('user_order')->where(['order_id'=>$OrderID])->find();
        $this->assign('OrderInfo',$OrderInfo);
        //获取订单中的所有商品id  并分割
        $goodsid = explode(',', $OrderInfo['goods_id']);
        //看单商品还是多商品
        if(count($goodsid) == 1){
            $goods = Db::name('goods')->where(['id'=>$OrderInfo['goods_id']])->find();
            $this->assign('goods',$goods);
            //用户信息
            $UserInfo = UserInfo(['id'=>$OrderInfo['user_id']]);
            $this->assign('UserInfo',$UserInfo);
            //商品数量
            $numb = $OrderInfo['num'];
            //系统参数
            $Config = Config();
            //Post请求
            if(IsPost()){
                //请求数据
                $Data = Param();
                //订单状态
                if($OrderInfo['status'] != 0){
                    return ['status'=>0,'message'=>'订单已支付，请勿重复支付！'];
                }

                //验证支付密码
                if(md5($Data['password']) != $UserInfo['password_pay']){
                    return ['status'=>0,'message'=>'支付密码不正确，请重新输入！'];
                }

                //积分支付
                if($Data['pay_type'] == 1){
                    $OrderSave['pay_amount'] = $OrderInfo['amount'];
                    //判断积分
                    if($OrderSave['pay_amount'] > $UserInfo['balance_1']){
                        return ['status'=>0,'message'=>'账户积分不足！'];
                    }
                    $jifen = $OrderSave['pay_amount'];//积分购物 用来返还
                    //更新积分
                    $UserSave['balance_1'] = $UserInfo['balance_1'] - $OrderSave['pay_amount'];
    //                $UserSave['balance_2'] = $UserInfo['balance_2'] + $OrderInfo['amount']; //消费返炁点
                }

                //积分 + 余额支付
                if($Data['pay_type'] == 2){
                    $OrderSave['pay_amount'] = $OrderInfo['amount'];
                    //判断积分 优先使用
                    if($OrderInfo['amount'] > $UserInfo['balance_1']){
                        if($UserInfo['balance_1'] + $UserInfo['balance_4'] < $OrderInfo['amount']){
                            return ['status'=>0,'message'=>'积分和余额不足！'];
                        }else{
                            $UserSave['balance_1'] = 0;
                            $UserSave['balance_4'] = $UserInfo['balance_4'] - $OrderInfo['amount'] + $UserInfo['balance_1'];
                        }
                    }else{
                        $UserSave['balance_1'] = $UserInfo['balance_1'] - $OrderInfo['amount'];
                    }
                    
                }

                //  余额支付
                if($Data['pay_type'] == 3){
                    $OrderSave['pay_amount'] = $OrderInfo['amount'];
                    //判断余额
                    if($OrderSave['pay_amount'] > $UserInfo['balance_4']){
                        return ['status'=>0,'message'=>'余额不足！'];
                    }
                    //更新余额
                    $UserSave['balance_4'] = $UserInfo['balance_4'] - $OrderSave['pay_amount'];
                    $jifen = 0;
                }

                //订单状态修改
                if($OrderInfo['order_type'] == 5){
                    $OrderSave['status'] = 4;
                }else{
                    $OrderSave['status'] = 1;
                }
                // $OrderSave['status'] = 1;
                
                $OrderSave['pay_type'] = $Data['pay_type'];
                $OrderSave['pay_time'] = time();
                if($Data['post_type']){
                    $OrderSave['post_type'] = $Data['post_type'];
                }else{
                    $OrderSave['post_type'] = 3;
                }
                
                
                //复购商品升级    买了成为会员
//                if($OrderInfo['order_type'] == 2){
//                    //自己没2级就升级
//                    if($UserInfo['level'] < 2){
//                        $UserSave['level'] = 2;
//                    }else{
//                        $UserSave['level'] = $UserInfo['level'];
//                    }
//                }else{
//                    $UserSave['level'] = $UserInfo['level'];
//                }
                //2021.5.26新增拼过团买东西都成为会员
                if($UserInfo['level'] == 1 && $UserInfo['is_pin'] == 1){
                    $UserSave['level'] = 2;
                }else{
                    $UserSave['level'] = $UserInfo['level'];
                }

                if($OrderInfo['order_type'] == 2){
                    //判断is_sheng 0 不升级 1vip  2代理
                    if($goods['is_sheng'] == 1){
                        if($UserInfo['level'] < 2){
                            $UserSave['level'] = 2;
                        }else{
                            $UserSave['level'] = $UserInfo['level'];
                        }
                    }elseif($goods['is_sheng'] == 2){
                        if($UserInfo['level'] < 3){
                            $UserSave['level'] = 3;
                        }else{
                            $UserSave['level'] = $UserInfo['level'];
                        }
                    }else{
                        $UserSave['level'] = $UserInfo['level'];
                    }
                }
//var_dump($UserSave);die;

                
                //秒杀
               if($OrderInfo['order_type'] == 4){
                   if($OrderInfo['num'] + $goods['sellnum'] > $goods['mnum']){
                       return ['status'=>0,'message'=>'库存不足'];
                   }
                   if($goods['etime'] < time()){
                       return ['status'=>0,'message'=>'秒杀时间已到,请等待下一轮活动'];
                   }
                }
                // var_dump($OrderInfo['pt_id']);die;
                //拼团
                if($OrderInfo['order_type'] == 5){
                    $pt = Db::name('user_pt')->where(['pt_id'=>$OrderInfo['pt_id']])->find();
                    
                    // var_dump($pt);
                    //自己不能参与自己参加过的拼团
                    $can = explode(',',$pt['can']);
                    if(in_array($UserInfo['id'],$can)){
                        return ['status'=>0,'message'=>'该商品已参加拼团,请换一个商品吧'];
                    }
                    //拼团状态为2  说明结束了
                    if($pt['status'] == 2){
                        return ['status'=>0,'message'=>'该商品拼团已结束'];
                    }
                    //参与人数<= 总人数
                    // var_dump($pt['can_people']);
                    // var_dump($pt['pt_people']);
                    if($pt['can_people'] >= $pt['pt_people']){
                        return ['status'=>0,'message'=>'拼团人数已达到,请换个商品!!!!'];
                    }
                    
                }

                //2021.6.24 积分专区限制每月购买次数
                if($OrderInfo['order_type'] == 1){
                    $xiangou = Config()['xiangou'];
                    if($UserInfo['countji'] >=$xiangou){
                        return ['status'=>0,'message'=>'超过积分专区每月限购次数'];
                    }
                    $UserSave['countji'] = $UserInfo['countji'] + 1;
                }

//                jicha($goods,$OrderInfo,$numb);die;
//var_dump($UserSave);die;
                //更新数据库
                if(Db::name('user_order')->where(['id'=>$OrderInfo['id']])->update($OrderSave)){

                    Db::name('user')->where(['id'=>$UserInfo['id']])->update($UserSave);
                    FinanceAdd($UserInfo['id'], $UserInfo['id'], $OrderInfo['amount'], $Data['pay_type'], 22, '商品购买',$OrderInfo['order_id']);

                   $higherInfo= Db::name('user')->where(['id'=>$UserInfo['recommend']])->find();
                    $GoodInfo = Db::name('goods')->where(['id'=>$OrderInfo['goods_id'] ])->find();
                    
                    //将总金额存入 setInc
                    Db::name('system_config')->where(['id'=>1])->setInc('month_all',$OrderInfo['amount']);
                    Db::name('system_config')->where(['id'=>1])->setInc('money_all',$OrderInfo['amount']);

    //                $fg_money=0;
                    $tj_money=0;

                    //团购
                    if($OrderInfo['order_type'] == 5){
                        if($OrderInfo['pt_id']){
                            $pt_status['status'] = 1;//1为激活该拼团
                            Db::name('user_pt')->where(['pt_id'=>$OrderInfo['pt_id']])->update($pt_status);
                        }
                        
                        //2021.5.26 参与拼团修改is_pin字段
                        //用户信息
                        $UserInfo = UserInfo(['id'=>$OrderInfo['user_id']]);
                        $is_pin['is_pin'] = 1;
                        Db::name('user')->where(['id'=>$UserInfo['id']])->update($is_pin);
                        
                        
                        //参团     修改人数  拼接参团人  
                        $this->tuan($OrderInfo);
                        $this->kai($OrderInfo,$GoodInfo);
//                        $this->dian($GoodInfo);
                    }
                    
                    //复购
//                    if($OrderInfo['order_type'] == 3){
//                        $this->quyu($OrderInfo,$GoodInfo,$numb);
//                    }
                    
                    //秒杀
                    if($OrderInfo['order_type'] == 4){
                        Db::name('goods')->where(['id'=>$OrderInfo['goods_id']])->setInc('sellnum',$OrderInfo['num']);
                        @$tj_money = $GoodInfo['reward_1']*$OrderInfo['num'];//推荐积分
                        @$tj_money1 = $GoodInfo['zhiyu']*$OrderInfo['num'];//推荐奖余额
                        //店铺级以上  直推奖励到余额    其他积分
                        // if($higherInfo['level'] >= 3){
                        //     $recommend['balance_4']=$higherInfo['balance_4']+$tj_money1;  //推荐奖励余额
                        //     $ms = '推荐奖余额';
                        //     FinanceAdd($UserInfo['recommend'], $UserInfo['id'], $tj_money1, 4, 11, $ms);
                        // }else{
                        //     $recommend['balance_1']=$higherInfo['balance_1']+$tj_money;  //推荐奖励积分
                        //     $ms = '推荐奖积分';
                        //     FinanceAdd($UserInfo['recommend'], $UserInfo['id'], $tj_money, 1, 11, $ms);
                        // }
                        $recommend['balance_4']=$higherInfo['balance_4']+$tj_money1;  //推荐奖励余额
                            $ms = '推荐奖余额';
                            if($tj_money1 > 0){
                                FinanceAdd($UserInfo['recommend'], $UserInfo['id'], $tj_money1, 4, 11, $ms,$OrderInfo['order_id']);
                            }
                            
                        // $recommend['person_achievement']=$higherInfo['person_achievement']+$GoodInfo['reward_1'];  //个人收益
                        Db::name('user')->where(['id'=>$UserInfo['recommend']])->update($recommend);
                        // FinanceAdd($UserInfo['recommend'], $UserInfo['id'], $tj_money, 4, 11, $ms);
                        $this->quyu($OrderInfo,$GoodInfo,$numb);
//                        $this->dian($GoodInfo);
                        Db::query('call add_recommend_num(:id,:num )',['id'=>$UserInfo['id'],'num'=>$OrderInfo['amount']]);    // team_num
                    }
                    
                    //礼包商品
                    if($OrderInfo['order_type'] == 2 || $OrderInfo['order_type'] == 3){//报单
                        @$tj_money = $GoodInfo['reward_1']*$OrderInfo['num'];//推荐奖
                        @$tj_money1 = $GoodInfo['zhiyu']*$OrderInfo['num'];//推荐奖
                        //店铺级以上  直推奖励到余额    其他积分
                        // if($higherInfo['level'] >= 3){
                        //     $recommend['balance_4']=$higherInfo['balance_4']+$tj_money1;  //推荐奖励余额
                        //     $ms = '推荐奖余额';
                        //     FinanceAdd($UserInfo['recommend'], $UserInfo['id'], $tj_money1, 4, 11, $ms);
                        // }else{
                        //     $recommend['balance_1']=$higherInfo['balance_1']+$tj_money;  //推荐奖励积分
                        //     $ms = '推荐奖积分';
                        //     FinanceAdd($UserInfo['recommend'], $UserInfo['id'], $tj_money, 1, 11, $ms);
                        // }
                        //2021.5.26  改成全部送余额
                        $recommend['balance_4']=$higherInfo['balance_4']+$tj_money1;  //推荐奖励余额
                        $ms = '推荐奖余额';
                        if($tj_money1 > 0){
                            FinanceAdd($UserInfo['recommend'], $UserInfo['id'], $tj_money1, 4, 11, $ms,$OrderInfo['order_id']);
                        }
                       
                        
                        //个人收益
                        Db::name('user')->where(['id'=>$UserInfo['recommend']])->update($recommend);
                        //店铺奖励
//                        $this->dian($GoodInfo);
                        // FinanceAdd($UserInfo['recommend'], $UserInfo['id'], $tj_money, 4, 11, $ms);
                        // Db::query('call add_recommend_num(:id,:num )',['id'=>$UserInfo['id'],'num'=>$OrderInfo['num']]);    //团队总台数 team_num
                         Db::query('call add_recommend_num(:id,:num )',['id'=>$UserInfo['id'],'num'=>$OrderInfo['amount']]);    // team_num
                        // //管理奖
//                         $this->guanli($GoodInfo);
                        // //区域奖
                        $this->quyu($OrderInfo,$GoodInfo,$numb);
                        
                        // //升级
                        uplevel($OrderInfo);
                        //级差奖
                        jicha($goods,$OrderInfo,$numb,$UserInfo['level']);

                    }
                    

                    return ['status'=>1,'message'=>'支付成功！'];
                }else{
                    return ['status'=>0,'message'=>'系统错误，请重试！'];
                }
            }
        }elseif(count($goodsid) > 1){
           
            //用户信息
            $UserInfo = UserInfo(['id'=>$OrderInfo['user_id']]);
            $this->assign('UserInfo',$UserInfo);

            //系统参数
            $Config = Config();
            //Post请求
            if(IsPost()){
                //请求数据
                $Data = Param();
                //订单状态
                if($OrderInfo['status'] != 0){
                    return ['status'=>0,'message'=>'订单已支付，请勿重复支付！'];
                }

                //验证支付密码
                if(md5($Data['password']) != $UserInfo['password_pay']){
                    return ['status'=>0,'message'=>'支付密码不正确，请重新输入！'];
                }

                //积分支付
                if($Data['pay_type'] == 1){
                    $OrderSave['pay_amount'] = $OrderInfo['amount'];
                    //判断积分
                    if($OrderSave['pay_amount'] > $UserInfo['balance_1']){
                        return ['status'=>0,'message'=>'账户积分不足！'];
                    }
                    $jifen = $OrderSave['pay_amount'];//积分购物 用来返还
                    //更新积分
                    $UserSave['balance_1'] = $UserInfo['balance_1'] - $OrderSave['pay_amount'];
    //                $UserSave['balance_2'] = $UserInfo['balance_2'] + $OrderInfo['amount']; //消费返炁点
                }

                //积分 + 余额支付
                if($Data['pay_type'] == 2){
                    //判断积分 优先使用
                    if($OrderInfo['amount'] > $UserInfo['balance_1']){
                        if($UserInfo['balance_1'] + $UserInfo['balance_4'] < $OrderInfo['amount']){
                            return ['status'=>0,'message'=>'积分和余额不足！'];
                        }else{
                            $UserSave['balance_1'] = 0;
                            $UserSave['balance_4'] = $UserInfo['balance_4'] - $OrderInfo['amount'] + $UserInfo['balance_1'];
                            $jifen = $UserInfo['balance_1'];//积分购物 用来返还
                        }
                    }else{
                        $UserSave['balance_1'] = $UserInfo['balance_1'] - $OrderInfo['amount'];
                        $jifen = $OrderInfo['amount'];//积分购物 用来返还
                    }
                    
                }

                //  余额支付
                if($Data['pay_type'] == 3){
                    $OrderSave['pay_amount'] = $OrderInfo['amount'];
                    //判断余额
                    if($OrderSave['pay_amount'] > $UserInfo['balance_4']){
                        return ['status'=>0,'message'=>'余额不足！'];
                    }
                    //更新余额
                    $UserSave['balance_4'] = $UserInfo['balance_4'] - $OrderSave['pay_amount'];
                    $jifen = 0;
                }

                //订单状态修改
                $OrderSave['status'] = 1;
                
                $OrderSave['pay_type'] = $Data['pay_type'];
                if($Data['post_type']){
                    $OrderSave['post_type'] = $Data['post_type'];
                }else{
                    $OrderSave['post_type'] = 3;
                }

                //更新数据库
                if(Db::name('user_order')->where(['id'=>$OrderInfo['id']])->update($OrderSave)){

                    Db::name('user')->where(['id'=>$UserInfo['id']])->update($UserSave);
                    FinanceAdd($UserInfo['id'], $UserInfo['id'], $OrderInfo['amount'], $Data['pay_type'], 22, '商品购买',$OrderInfo['order_id']);

                   $higherInfo= Db::name('user')->where(['id'=>$UserInfo['recommend']])->find();
                    
                    
                    //将总金额存入 setInc
                    Db::name('system_config')->where(['id'=>1])->setInc('month_all',$OrderInfo['amount']);
                    Db::name('system_config')->where(['id'=>1])->setInc('money_all',$OrderInfo['amount']);

    //                $fg_money=0;
                    $tj_money=0;
                    
                    foreach ($goodsid as $key => $value) {
                        $UserInfo = UserInfo(['id'=>$OrderInfo['user_id']]);
                        $higherInfo= Db::name('user')->where(['id'=>$UserInfo['recommend']])->find();
                        $GoodInfo = Db::name('goods')->where(['id'=>$value])->find();
                        // $numb = $OrderInfo['num'][$key];
                        $nums = explode(',',$OrderInfo['num']);
                        $numb = $nums[$key];
                        //复购
//                        if($GoodInfo['goods_type'] == 3){
//                            $this->quyu($OrderInfo,$GoodInfo,$numb);
//                        }
                        //礼包商品
                        if($GoodInfo['goods_type'] == 2 || $GoodInfo['goods_type'] == 3){//报单
                            @$tj_money = $GoodInfo['reward_1']*$numb;//推荐奖
                            @$tj_money1 = $GoodInfo['zhiyu']*$numb;//推荐奖
                            //店铺级以上  直推奖励到余额    其他积分
                            // if($higherInfo['level'] >= 3){
                            //     $recommend['balance_4']=$higherInfo['balance_4']+$tj_money1;  //推荐奖励余额
                            //     $ms = '推荐奖余额';
                            //     FinanceAdd($UserInfo['recommend'], $UserInfo['id'], $tj_money1, 4, 11, $ms);
                            // }else{
                            //     $recommend['balance_1']=$higherInfo['balance_1']+$tj_money;  //推荐奖励积分
                            //     $ms = '推荐奖积分';
                            //     FinanceAdd($UserInfo['recommend'], $UserInfo['id'], $tj_money, 1, 11, $ms);
                            // }
                            $recommend['balance_4']=$higherInfo['balance_4']+$tj_money1;  //推荐奖励余额
                            $ms = '推荐奖余额';
                            if($tj_money1 > 0){
                                FinanceAdd($UserInfo['recommend'], $UserInfo['id'], $tj_money1, 4, 11, $ms,$OrderInfo['order_id']);
                            }
                            
                            
                            //个人收益
                            Db::name('user')->where(['id'=>$UserInfo['recommend']])->update($recommend);
                            //店铺奖励
//                            $this->dian($GoodInfo);
                            
                             Db::query('call add_recommend_num(:id,:num )',['id'=>$UserInfo['id'],'num'=>$GoodInfo['price']]);    // team_num
                            
                            // //区域奖
                            $this->quyu($OrderInfo,$GoodInfo,$numb);

                            // //升级
                            uplevel($OrderInfo);
                            //级差奖
                            jicha($GoodInfo,$OrderInfo,$numb,$UserInfo['level']);
                            
                        }
                    } 
                    
                    return ['status'=>1,'message'=>'支付成功！'];
                }else{
                    return ['status'=>0,'message'=>'系统错误，请重试！'];
                }
            }
        }
        
        
        return $this->fetch('OrderPay');
    }


    public function OrderWeChatGZPay(){
        $post_type = Param('post_type');
        if($post_type== 1 || $post_type==2){
             Db::name('user_order')->where(['order_id'=>Param('order_id')])->update(['post_type'=>$post_type]);
        }
       
        $Config = Config();
        $this->assign('title',$Config['web_name']);
        $OrderInfo = Db::name('user_order')->where(['order_id'=>Param('order_id')])->find();
        // dump($OrderInfo);die;
        // dump($_SERVER['HTTP_HOST']."/index.php/open/OrderWeChatGZNotify");die;
        Vendor('WxPayv3.JSAPI');
        $tools = new \JsApiPay();
        $openid = $tools->GetOpenid();
        // dump($openid);
        $openid = $openid['openid'];
       
        // $info = $this->get_user_all();
        // $info = json_decode($info,true);
        // dump($info);die;
        $total_money =$OrderInfo['amount'];
        //  $total_money =0.01;
        $input = new \WxPayUnifiedOrder();
        $input->SetBody('商城消费');//商品或支付单简要描述
        $input->SetAttach($OrderInfo['id']); //附加数据
        $input->SetOut_trade_no($OrderInfo['order_id']);//传的值
        $input->SetTotal_fee($total_money*100);
        $input->SetTime_start(date("YmdHis"));
        $input->SetTime_expire(date("YmdHis", time() + 600));
        $input->SetGoods_tag("商城消费");
        $url = $_SERVER['HTTP_HOST']."/index.php/open/OrderWeChatGZNotify";
        $input->SetNotify_url($url);
        $input->SetTrade_type("JSAPI");
        $input->SetOpenid($openid);
        // dump($openid);
        
        $or = \WxPayApi::unifiedOrder($input);
        // dump($or);die;

        $jsApiParameters = $tools->GetJsApiParameters($or);
        $this->assign('jsApiParameters',$jsApiParameters);
        $this->assign("total_money",$total_money);
        return $this->fetch("1");
    }
    
     private $appId = 'wx5b5fbd4cdafaf65f';
    private $appSecret = '480a03ffeae1e9c7b881c2be9bfa3a9f';
    /**
     * 1、获取微信用户信息，判断有没有code，有使用code换取access_token，没有去获取code。
     * @return array 微信用户信息数组
     */
    public function get_user_all()
    {
        if (!isset($_GET['code'])) {//没有code，去微信接口获取code码
            $callback = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];//微信服务器回调url，这里是本页url;注意：：这里回调的url是http://www.klda.com/index.php。如果想要获取完整的路径用 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']
            $this->get_code($callback);
        } else {//获取code后跳转回来到这里了
            $code = $_GET['code'];
            $data = $this->get_access_token($code);//获取网页授权access_token和用户openid
            $data_all = $this->get_user_info($data['access_token'], $data['openid']);//获取微信用户信息
            //原来的返回
            // return json($data_all);
            //修改返回json
            return json_encode($data_all,true);
        }
    }
    /**
     * 2、用户授权并获取code
     * @param string $callback 微信服务器回调链接url
     */
    private function get_code($callback)
    {
        $appid = $this->appId;
        $scope = 'snsapi_userinfo';
        $state = md5(uniqid(rand(), TRUE));//唯一ID标识符绝对不会重复
        $url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' . $appid . '&redirect_uri=' . urlencode($callback) . '&response_type=code&scope=' . $scope . '&state=' . $state . '#wechat_redirect';
        header("Location:$url");
    }

    /**
     * 3、使用code换取access_token
     * @param string 用于换取access_token的code，微信提供
     * @return array access_token和用户openid数组
     */
    private function get_access_token($code)
    {
        $appid = $this->appId;
        $appsecret = $this->appSecret;
        $url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid=' . $appid . '&secret=' . $appsecret . '&code=' . $code . '&grant_type=authorization_code';
        $user = json_decode(file_get_contents($url));
        if (isset($user->errcode)) {
            echo 'error:' . $user->errcode . '<hr>msg  :' . $user->errmsg;
            exit;
        }
        $data = json_decode(json_encode($user), true);//返回的json数组转换成array数组
        return $data;
    }

    /**
     * 4、使用access_token获取用户信息
     * @param string access_token
     * @param string 用户的openid
     * @return array 用户信息数组
     */
    private function get_user_info($access_token, $openid)
    {
        $url = 'https://api.weixin.qq.com/sns/userinfo?access_token=' . $access_token . '&openid=' . $openid . '&lang=zh_CN';
        $user = json_decode(file_get_contents($url));
        if (isset($user->errcode)) {
            echo 'error:' . $user->errcode . '<hr>msg  :' . $user->errmsg;
            exit;
        }
        $data = json_decode(json_encode($user), true);//返回的json数组转换成array数组
        return $data;
    }

    /**
     * 订单删除
     * @return array
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function OrderDelete(){
        //Post请求
        if(IsPost()){
            //订单信息
            $OrderID = Param('order_id');
            $OrderInfo = Db::name('user_order')->where(['order_id'=>$OrderID])->find();

            //删除订单
            if(Db::name('user_order')->where(['id'=>$OrderInfo['id']])->delete()){
                return ['status'=>1,'message'=>'删除成功！'];
            }else{
                return ['status'=>0,'message'=>'系统错误，请重试！'];
            }
        }
    }

    /**
     * 订单收货
     * @return array
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function OrderSure(){
        //Post请求
        if(IsPost()){
            //订单信息
            $OrderID = Param('order_id');
            $OrderInfo = Db::name('user_order')->where(['order_id'=>$OrderID])->find();

            //订单收货
            if(Db::name('user_order')->where(['id'=>$OrderInfo['id']])->update(['status'=>3])){
                return ['status'=>1,'message'=>'收货成功！'];
            }else{
                return ['status'=>0,'message'=>'系统错误，请重试！'];
            }
        }
    }
    
    //分享
    public function fenx(){
        ob_end_clean();
        //获取该订单信息   状态为4的是还没有拼团成功的
        $orderinfo = Db::name('user_order')->where(['order_id'=>Param('order_id'),'status'=>4])->find(); 
        $goodinfo =  Db::name('goods')->where(['id'=>$orderinfo['goods_id']])->find(); 
        // 从现在文件载入一幅图像 背景图
        $im = imagecreatefromjpeg($_SERVER['DOCUMENT_ROOT'].'/uploads/goods/20210330/背景.jpg');
        // 从现在文件载入一幅图像 二维码图片
        //生成二维码图片
        $url = 'http://'.$_SERVER['HTTP_HOST'] . '/index.php/index/goodsdetail.html?&goods_id='.$goodinfo['id'].'&pt_id='.$orderinfo['pt_id'];
        $qrpath = $this->addQrcode($url,$orderinfo['pt_id']);
        $qrpath = 'http://'.$_SERVER['HTTP_HOST'] . '/uploads/qrcode/' . $orderinfo['pt_id'].'.png';
        
        $codeIm = imagecreatefrompng($qrpath);
        $codeIm1 = imagecreatefromjpeg($_SERVER['DOCUMENT_ROOT'].$goodinfo['logo_url']);
        // 获取图片的宽、高
        list($w, $h) = getimagesize($_SERVER['DOCUMENT_ROOT'].'/uploads/qrcode/21.png');
        list($w1, $h1) = getimagesize($_SERVER['DOCUMENT_ROOT'].$goodinfo['logo_url']);
        //引入字体文件
        $boldFontFile = __DIR__ . '/STXINWEI.TTF';
        // 为画布分配一个颜色，主要用于写文字
        $font_color_1 = imagecolorallocate($im, 255, 0, 0);
        $title = '商品名称 : ' . $goodinfo['name'];
        $title1 = '商品价格 : ' . $goodinfo['price'];
        
        //缩放比例
        // $per=round(700/$w1,2);
        // $n_w=$w1*$per;
        // $n_h=$h1*$per;
        //拷贝图像并调整图像的大小  200左右  1000上下  
        // imagecopyresized($im, $codeIm1, 0, 0, 100, 100, $n_w, $n_h, $w1, $h1);//背景图
        imagecopyresized($im, $codeIm1, 0, 0, 100, 100, 700, 800, $w1, $h1);//背景图
        imagecopyresized($im, $codeIm, 20, 550, 10, 10, 150, 150, $w, $h); //二维码
        // 向画布中写文字   30字体大小 0倾斜度  95左右距离 490上下距离
        imagettftext($im, 25, 0, 300, 600, $font_color_1, $boldFontFile, $title);
        imagettftext($im, 25, 0, 300, 650, $font_color_1, $boldFontFile, $title1);
        //  imagecopy($im,$codeIm,200, 1000, 0, 0,$w, $h);
        //输出图片
        header('Content-Type:image/jpeg');
        imagejpeg($im);
        //释放空间
        // imagedestroy($im);
        // imagedestroy($codeIm);
    }
    
    /**
     * 二维码生成
     * @param $url
     * @param $id
     * @return string
     */
    public function addQrcode($url,$id){
        Vendor('phpqrcode.phpqrcode');
        //生成二维码图片
        $object = new \QRcode();

        $path = $_SERVER['DOCUMENT_ROOT']."/uploads/qrcode/";

        $ad = $path.$id.'.png';
        $errorCorrectionLevel ='L' ;//容错级别
        $matrixPointSize = 6;//生成图片大小

        $object->png($url,  $ad, $errorCorrectionLevel, $matrixPointSize, 2);
        return $ad;
    }
    
    public function OrderEdit(){
        //订单信息
        // var_dump(Param('id'));die;
        $OrderInfo = OrderInfo(['order_id'=>Param('id')]);
        // var_dump($OrderInfo);die;
        $this->assign('OrderInfo',$OrderInfo);

        //订单信息
        // $GoodsInfo = GoodsInfo(['id'=>$OrderInfo['goods_id']]);
        $goods_id = explode(',', $OrderInfo['goods_id']);
        $num = explode(',', $OrderInfo['num']);
        foreach ($goods_id as $k=>$v) {
            $GoodsInfo = GoodsInfo(['id'=>$v]);
            $GoodsInfo['num'] = $num[$k];
            $infos[] = $GoodsInfo;
        }
        // echo "<pre>";
        // var_dump($infos);die;
        $this->assign('GoodsInfo',$infos);

        //会员信息
        $UserInfo = UserInfo(['id'=>$OrderInfo['user_id']]);
        $this->assign('UserInfo',$UserInfo);
        
        //拼团信息
        if($OrderInfo['order_type'] == 5){
            $pt = Db::name('user_pt')->where(['pt_id'=>$OrderInfo['pt_id']])->find();
            //获取拼团人头像
            $can = explode(',',$pt['can']);
            foreach ($can as $val){
                $caninfo[] = UserInfo(['id'=>$val]);
            }
            $this->assign('caninfo',$caninfo);
            //获取得到人头像
            $zhong = explode(',',$pt['zhong']);
            foreach ($zhong as $value){
                $zhonginfo[] = UserInfo(['id'=>$value]);
            }
            $this->assign('zhonginfo',$zhonginfo);
        }

        //Post请求操作
        if(IsPost()){
            //请求数据
            $Data = Param();
            if(!empty($Data['recommend'])){
                $RecommendInfo = UserInfo(['username'=>$Data['recommend']]);
                if(empty($RecommendInfo)){
                    return ['status'=>0,'message'=>'推荐账号不存在'];
                }
            }
            //向表中添加数据
            if(Db::name('user')->update($Data)){
                return ['status'=>1,'message'=>'修改成功'];
            }else{
                return ['status'=>0,'message'=>'系统错误，请重试'];
            }
        }

        return $this->fetch('OrderEdit');
    }


    /**
     * 添加购物车
     * @return array
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function AddCart(){
        //Post请求
        if(IsPost()){
            $Num = Param('num');    //数量  默认1
            $goodsid = Param('Goodsid'); //商品id
            //判断是否登录账号
            $UserID = Session::get('user_id');
            // var_dump($Num);
            // var_dump($goodsid);
            // var_dump($UserID);die;

            if(empty($UserID) || $UserID==NULL){
                return ['status'=>0,'message'=>'未登录账号，请先登录！'];
            }

            $NowCart = Db::name('user_cart')->where(["user_id"=>$UserID])->find();  //当前购物车内容
            // var_dump($NowCart);die;
            if (empty($NowCart)){
                $CartAdd['user_id'] = $UserID;
                $CartAdd['num'] = $Num;
                $CartAdd['goods_id'] = $goodsid;
                Db::name('user_cart')->insert($CartAdd);
            }else{
                //查看此商品是否已存在购物车中
                $CartWhere['goods_id'] = $goodsid;
                $CartWhere['user_id'] = $UserID;
                $CartInfo = Db::name('user_cart')->where($CartWhere)->find();
                // var_dump($CartInfo);
                //购物车是否存在 不存在就添加
                if(empty($CartInfo)){
                    $CartAdd['user_id'] = $UserID;
                    $CartAdd['num'] = $Num;
                    $CartAdd['goods_id'] = $goodsid;
                    Db::name('user_cart')->insert($CartAdd);
                }else{
                    Db::name('user_cart')->where(['id'=>$CartInfo['id']])->setInc('num',$Num);
                }

            }

            return ['status'=>1,'message'=>'添加购物车成功'];
        }
    }

    /**
     * 购物车
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function UserCart(){
        //拼团
        $pt_id = Param('pt_id');
        if($pt_id){
            $pt_id = $pt_id;
        }else{
            $pt_id = 0;
        }
        $this->assign('pt_id',$pt_id);

        //会员信息
        $UserInfo = UserInfo(['id'=>Session::get('user_id')]);
        $this->assign('UserInfo',$UserInfo);

        $Address = Db::name('user_address')->where(['user_id'=>$UserInfo['id'],'is_default'=>1])->find();
        if(!$Address){
            echo "<script>alert('请先填写地址');location.href='/index.php/user/addresslist'</script>";die;
        }
       // var_dump($Address);die;

        //购物车信息
        $CartList = Db::name('user_cart')->where(['user_id'=>Session::get('user_id')])->select();
        
        foreach ($CartList as $k=>$v){
            // $CartList[$k]['goods_info'] = Db::name('goods')->where(['id'=>$v['goods_id']])->find();
            $goodsinfo = Db::name('goods')->where(['id'=>$v['goods_id']])->find();
            if($goodsinfo['goods_type'] == 3){
                if($UserInfo['level'] == 6){
                    $goodsinfo['price'] = $goodsinfo['sjprice'];
                }elseif($UserInfo['level'] == 5){
                    $goodsinfo['price'] = $goodsinfo['qxprice'];
                }elseif($UserInfo['level'] == 4){
                    $goodsinfo['price'] = $goodsinfo['dpprice'];
                }elseif($UserInfo['level'] == 3){
                    $goodsinfo['price'] = $goodsinfo['dlprice'];
                }elseif($UserInfo['level'] == 2){
                    $goodsinfo['price'] = $goodsinfo['hyprice'];
                }elseif($UserInfo['level'] == 7){
                    $goodsinfo['price'] = $goodsinfo['shprice'];
                }elseif($UserInfo['level'] == 8){
                    $goodsinfo['price'] = $goodsinfo['hhrprice'];
                }else{
                    $goodsinfo['price'] = $goodsinfo['price'];
                }
            }else{
                $goodsinfo['price'] = $goodsinfo['price'];
            }

            $CartList[$k]['goods_info'] = $goodsinfo;
        }
        $this->assign("CartList",$CartList);
//         echo "<pre>";
// var_dump($CartList);die;
        //购物车产品数量
        $CartCount = count($CartList);
        $this->assign('CartCount',$CartCount);

        //系统参数
        $Config = Config();
        $this->assign("Config",$Config);

        return $this->fetch("UserCart");
    }

    /**
     * 删除购物车商品
     * @return array
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function DelCart(){
        //Post请求
        if(IsPost()) {
            $Data = Param();    //商品属性ID
            $DelWhere['id'] = array('in',$Data['cart_id_array']); //购物车ID
            if(Db::name('user_cart')->where($DelWhere)->delete()){  //删除表中数据
                return ['status'=>1,'message'=>'删除成功'];
            }else{
                return ['status'=>0,'message'=>'系统错误，请稍后再试'];
            }
        }
    }

    //更新购物车
    public function upche(){
        if(IsPost()) {
            $Data = Param();  
            //将购物车的所有修改后数量列出来
            $nums = explode(',', $Data['NumStr']);  
            $mycar = Db::name('user_cart')->where(['user_id'=>Session::get('user_id')])->order('id asc')->select();
            foreach ($mycar as $key => $value) {
               if($value['num'] != $nums[$key]){
                    $newdata['num'] = $nums[$key];
                    Db::name('user_cart')->where(['id'=>$value['id']])->update($newdata);
               }
            }
            return ['status'=>1];
        }
    }
    
}
